#include "GMReturnPing.h"
#include "Factory.h"
#include "TimerMS.h"
#include "MessageQueue.h"
#include "ClientManager.h"
#include "ClientPlayerManager.h"
#include "ServerManager.h"

#include <iostream>

GMReturnPing::GMReturnPing()
{
	m_id = -1;
}

void GMReturnPing::Execute()
{
	// callled on server
	TheServerManager::Instance()->SyncPositions(m_id, m_pos);
	std::cout << "Return ping executed" << std::endl;
}

bool GMReturnPing::Read(SocketMessage* sm)
{
	// called on server

	int tempTS = 0;
	sm->ReadInt(&tempTS);
	sm->ReadInt(&m_id);
	m_timeStamp = (unsigned int)tempTS;
	//SDL_Delay(1500);
	//TheTimer::Instance()->UpdateTime();
	//float curTime = TheTimer::Instance()->GetTime();
	//float ts = m_timeStamp;
	//curTime -= ts;
	//SDL_Delay(1000);
	m_latency = TheTimerMS::Instance()->GetTimeMS() - m_timeStamp;
	std::cout << "latency in ms: " << m_latency << std::endl;
	TheMsgQueue::Instance()->AddLagTime(m_latency);
	
	sm->ReadFloat(&m_pos.x);
	sm->ReadFloat(&m_pos.y);
	sm->ReadFloat(&m_pos.z);

	return true;
}

void GMReturnPing::Write(SocketMessage* sm)
{
	sm->WriteString("GMReturnPing");
	sm->WriteInt(m_timeStamp);
	sm->WriteInt(TheClientManager::Instance()->GetID());
	Vec3fNet pos = TheCPManager::Instance()->GetClientPos(TheClientManager::Instance()->GetID());
	sm->WriteFloat(pos.x);
	sm->WriteFloat(pos.y);
	sm->WriteFloat(pos.z);
}